<?php

namespace app\model\system;

use app\model\BaseModel;
use albert\traits\ModelTrait;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

/**
 * 附件分类表 Model
 * Class SystemAttachmentCategory
 * @package app\models\system
 */
class SystemAttachmentCategory extends BaseModel
{
    use ModelTrait;

    /**
     * 初始化查询条件
     * Author: Albert3306
     * Date: 2021/7/2
     * @param $where
     * @param null $model
     * @return SystemAttachmentCategory|mixed
     */
    public static function initWhere($where, $model = null)
    {
        $model = $model ?? new self;
        if (isset($where['pid']) && $where['pid'] !== '') $model = $model->where('pid', $where['pid']);
        if (isset($where['likeName']) && $where['likeName'] !== '') $model = $model->whereLike('name', '%' . $where['likeName'] . '%');
        return $model;
    }

    /**
     * 获取分类图
     * Author: Albert3306
     * Date: 2021/7/2
     * @param $name
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function getAll($name): array
    {
        return self::tidyMenuTier(self::initWhere(['likeName' => $name])->select());
    }

    /**
     * 处理分类
     * Author: Albert3306
     * Date: 2021/7/2
     * @param $menusList
     * @param int $pid
     * @param array $navList
     * @return array
     */
    public static function tidyMenuTier($menusList, int $pid = 0, array $navList = []): array
    {
        foreach ($menusList as $k => $menu) {
            $menu = $menu->getData();
            if ($menu['pid'] == $pid) {
                unset($menusList[$k]);
                $menu['child'] = self::tidyMenuTier($menusList, $menu['id']);
                $navList[] = $menu;
            }
        }
        return $navList;
    }

    /**
     * 获取分类下拉列表
     * Author: Albert3306
     * Date: 2021/7/2
     * @param int $id
     * @param int $type
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function getCateList(int $id = 10000, int $type = 0): array
    {
        $model = new self();
        if ($id == 0)
            $model->where('pid', $id);
        if ($type == 1)
            $model->where('pid', 0);
        $list = sort_list_tier($model->select()->toArray());
        $options = [['value' => 0, 'label' => '所有分类']];
        foreach ($list as $cateName) {
            $options[] = ['label' => $cateName['html'] . $cateName['name'], 'value' => $cateName['id']];
        }
        return $options;
    }
}